package com.cz.zslu.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cz.zslu.common.ReturnObject;
import com.cz.zslu.entity.*;
import com.cz.zslu.interceptor.BaseContextHandler;
import com.cz.zslu.interceptor.IgnoreAuth;
import com.cz.zslu.rest.BaseController;
import com.cz.zslu.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * <p>
 * 图片管理 前端控制器
 * </p>
 *
 * @author Bruce
 * @since 2019-06-10
 */
@RestController
@RequestMapping("/sys/photoattachment")
@Api(description = "图片管理")
public class PhotoAttachmentController extends BaseController<PhotoAttachmentService, PhotoAttachment> {

    @Autowired
    private IBaseAttachmentService iBaseAttachmentService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private PhotoAlbumService photoAlbumService;

    @Autowired
    private CompanyContactService companyContactService;


    /**
     * 文件路径
     */
    @Value("${file_address}")
    private String storePath;


    @ApiOperation("获取该相册下全部图片")
//    @IgnoreAuth
    @RequestMapping(value = "/getPage", method = RequestMethod.POST)
    public ReturnObject<List<PhotoAttachment>> getPage(@ApiParam("每页条数") @RequestParam(defaultValue = "10") int limit,
                                                       @ApiParam("页数") @RequestParam(defaultValue = "1") int offset,
                                                       @ApiParam("相册id") @RequestParam Long albumId) {
        EntityWrapper<PhotoAttachment> ew = new EntityWrapper<>();
        ew.eq("state", 0);
        ew.eq("album_id", albumId);
        ew.orderBy("crt_time", false);
        Page<PhotoAttachment> obj = baseService.selectPage(new Page<>(offset, limit), ew);
        return new ReturnObject<>(0, "获取成功", obj.getTotal(), obj.getPages(), obj.getRecords());
    }

    @ApiOperation("通过id获取详情")
    @IgnoreAuth
    @RequestMapping(value = "/findInfoById", method = RequestMethod.POST)
    public ReturnObject<PhotoAttachment> findInfoById(@ApiParam("id") @RequestParam Long id) {

        return new ReturnObject<>(0, "获取成功", baseService.selectById(id));
    }


    @ApiOperation("新增")
    @RequestMapping(value = "/savePhotoAttachment", method = RequestMethod.POST)
    public ReturnObject<PhotoAttachment> savePhotoAttachment(@ApiParam("相册id") @RequestParam Long albumId,
                                                             @ApiParam("图片id") @RequestParam Long[] photoIds) {
        List<BaseAttachment> attachments = iBaseAttachmentService.selectBatchIds(Arrays.asList(photoIds));
        for (int i = 0; i < attachments.size(); i++) {
            PhotoAttachment info = new PhotoAttachment();
            info.setAlbumId(albumId);
            info.setPhotoId(attachments.get(i).getId());
            info.setPhotoName(attachments.get(i).getOriginalName().split("\\.")[0]);
            info.setPhotoUrl(attachments.get(i).getAddress());
            baseService.insert(info);
            PhotoAlbum photoAlbum = photoAlbumService.selectById(albumId);
            photoAlbum.setCapacity(photoAlbum.getCapacity() + Long.valueOf(attachments.get(i).getSize()));
            photoAlbumService.updateById(photoAlbum);

        }
        return new ReturnObject<>(0, "新增成功", null);
    }

    @ApiOperation("添加图片名称）")
    @RequestMapping(value = "/addPhotoName", method = RequestMethod.POST)
    public ReturnObject<PhotoAttachment> addCover(@ApiParam("id") @RequestParam Long id,
                                                  @ApiParam("图片名称") @RequestParam String photoName) {

        PhotoAttachment info = baseService.selectById(id);
        info.setPhotoName(photoName);
        baseService.updateById(info);
        return new ReturnObject<>(0, "修改成功", null);
    }

    @ApiOperation("统一添加水印")
    @RequestMapping(value = "/addWatermark", method = RequestMethod.POST)
    public ReturnObject<PhotoAttachment> addWatermark(@ApiParam("相册id") @RequestParam Long albumId,
                                                      @ApiParam("是否有公司名称") @RequestParam Integer isCompanyName,
                                                      @ApiParam("是否有公司网址") @RequestParam Integer isCompanyNet,
                                                      @ApiParam("水印位置设置 0:在左上角、1:在中间、2:在右下角") @RequestParam Integer location) {
        //如果albumId为空，那对该店铺下所有相册中的图片进行统一加水印处理
        SysUser sysUser = iSysUserService.selectById(BaseContextHandler.getUserID());
        List<PhotoAttachment> list = new ArrayList<PhotoAttachment>();
        if (albumId == null) {
            List<PhotoAlbum> albums = photoAlbumService.selectList(new EntityWrapper<PhotoAlbum>().eq("store_id", sysUser.getStoreId()));
            if (albums != null && albums.size() > 0) {
                for (int j = 0; j < albums.size(); j++) {
                    List<PhotoAttachment> attachments = baseService.selectList(new EntityWrapper<PhotoAttachment>().eq("album_id", albums.get(j).getId()));
                    list.addAll(attachments);
                }
            }
        } else {
            list = baseService.selectList(new EntityWrapper<PhotoAttachment>().eq("album_id", albumId));
        }
        CompanyContact companyContact = companyContactService.selectOne(new EntityWrapper<CompanyContact>().eq("store_id", sysUser.getStoreId()));

        String word = "";
        if (isCompanyName == 1) {
            word = companyContact.getCompanyName();
        }
        if (isCompanyNet == 1 && word != "") {
            word = word+"\r\n" + companyContact.getCompanyNet();
        }
        if (list != null && list.size() > 0) {

            for (int i = 0; i < list.size(); i++) {
                PhotoAttachment info = baseService.selectById(list.get(i).getId());
                //图片源路径
                String source = storePath + info.getPhotoUrl();
                BaseAttachment baseAttachment = markImageByMoreText(source, word, location);
                info.setPhotoUrl(baseAttachment.getAddress());
                info.setPhotoId(baseAttachment.getId());
                baseService.updateById(info);

            }
        }

        return new ReturnObject<>(0, "修改成功", null);
    }


    @ApiOperation("批量修改图片名称")
    @RequestMapping(value = "/updatePhotoName", method = RequestMethod.POST)
    public ReturnObject<PhotoAttachment> updatePhotoInfo(@ApiParam("相册id") @RequestParam Long albumId,
                                                         @ApiParam("图片名称") @RequestParam String photoName) {

        List<PhotoAttachment> list = baseService.selectList(new EntityWrapper<PhotoAttachment>().eq("album_id", albumId));
        for (PhotoAttachment info : list) {
            info.setPhotoName(photoName);
            baseService.updateById(info);
        }
        return new ReturnObject<>(0, "修改成功", null);
    }


    @ApiOperation("批量删除")
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public ReturnObject<PhotoAttachment> del(@ApiParam("ids") @RequestParam Long[] ids) {
        List<PhotoAttachment> list = baseService.selectBatchIds(Arrays.asList(ids));
        for (PhotoAttachment info : list) {
            info.setState(1);
            baseService.updateById(info);

        }
        return new ReturnObject<>(0, "删除成功", null);
    }

    @ApiOperation("批量移动")
    @RequestMapping(value = "/move", method = RequestMethod.POST)
    public ReturnObject<PhotoAttachment> move(@ApiParam("ids") @RequestParam Long[] ids, @ApiParam("相册id") @RequestParam Long albumId) {
        List<PhotoAttachment> list = baseService.selectBatchIds(Arrays.asList(ids));
        for (PhotoAttachment info : list) {
            info.setAlbumId(albumId);
            baseService.updateById(info);
        }
        return new ReturnObject<>(0, "删除成功", null);
    }


    /**
     * @param source   图片源路径
     * @param word     水印文字
     * @param location 水印位置
     * @return
     */
    private BaseAttachment markImageByMoreText(String source, String word, Integer location) {

        BaseAttachment info = new BaseAttachment();
        try {
            Long fileSize = null;
            //读取原图片信息
            File file = new File(source);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            String ymd = sdf.format(new Date());
            String savePath = storePath;

            String newFileName = "";
            String fileExt = "";
            String saveFileName = ymd;

            savePath += File.separator + ymd + File.separator;
            File dirFile = new File(savePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            //文字大小
            int size = 30;
            //设置水印字体样式
            Font font = new Font("宋体", Font.PLAIN, size);
            Image img = ImageIO.read(file);
            JLabel label = new JLabel(word);
            FontMetrics metrics = label.getFontMetrics(font);
            int width = metrics.stringWidth(label.getText());//文字水印的宽度

            //图片宽
            int imgWidth = img.getWidth(null);
            //图片高
            int imgHeight = img.getHeight(null);

            //加水印
            BufferedImage bi = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bi.createGraphics();
            g.drawImage(img, 0, 0, imgWidth, imgHeight, null);

            //根据图片的背景设置水印颜色
            g.setColor(Color.BLACK);
            int x = 0;
            int y = 0;
            if (location == 0) {
                x = 0;
                y = 40;

            } else if (location == 1) {
                x = imgWidth / 2 - width / 2;
                y = imgHeight / 2;
            } else {
                x = imgWidth - width;
                y = imgHeight - 10;
            }

            g.setFont(font);
            g.drawString(word, x, y);
            g.dispose();

            try {
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                /**
                 *  文件后缀
                 */
                fileExt = source.substring(source.lastIndexOf(".") + 1).toLowerCase();


                info.setFileExt(fileExt);
                /**
                 * 重定义文件名
                 */
                newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;

                info.setAttName(newFileName);

                //输出图片
                File sf = new File(savePath, newFileName);
                ImageIO.write(bi, fileExt, sf); // 保存图片
                if (sf.exists() && sf.isFile()) {
                    FileInputStream fis = new FileInputStream(sf);
                    fileSize = fis.getChannel().size();
                }
                info.setSize(fileSize.toString());
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            /**
             * 保存入库
             */
            saveFileName += File.separator + newFileName;
            info.setAddress(saveFileName);
            iBaseAttachmentService.insert(info);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }


    /**
     * 给图片添加多个文字水印、可设置水印文字旋转角度
     *
     * @param source    需要添加水印的图片路径（如：F:/images/6.jpg）
//     * @param outPut    添加水印后图片输出路径（如：F:/images/）
     * @param imageName 图片名称（如：11111）
     * @param imageType 图片类型（如：jpg）
     * @param color     水印文字的颜色
     * @param word      水印文字
     * @param degree    水印文字旋转角度，为null表示不旋转
     */
    public static String markImageByMoreText(String source, String output, String imageName, String imageType, Color color, String word, Integer degree) {
        source = "/Users/32sky/Downloads/汽配1.jpg";
        output = "/Users/32sky/Downloads/";
        word = "中国共产党万岁" + "\n" + "www.baidu.com";
        String result = "添加文字水印出错";
        Long fileSize = null;
        try {
            //读取原图片信息
            File file = new File(source);
            if (!file.isFile()) {
                return file + " 不是一个图片文件!";
            }
            imageName = file.getName();
            imageType = imageName.split("\\.")[1];

            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

            /**
             * 重定义文件名
             */
            imageName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + imageType;
            Image img = ImageIO.read(file);
            //图片宽
            int imgWidth = img.getWidth(null);
            //图片高
            int imgHeight = img.getHeight(null);
            //文字大小
            int size = 20;
            //加水印
            BufferedImage bi = new BufferedImage(imgWidth, imgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bi.createGraphics();
            g.drawImage(img, 0, 0, imgWidth, imgHeight, null);
            //设置水印字体样式
            Font font = new Font("宋体", Font.PLAIN, size);
            //根据图片的背景设置水印颜色
            g.setColor(Color.BLACK);
            JLabel label = new JLabel(word);
            FontMetrics metrics = label.getFontMetrics(font);
            int width = metrics.stringWidth(label.getText());//文字水印的宽
            int x = imgWidth - width;
            int y = imgHeight-10;
//            int space = height/size;
//            for(int i=0;i<space;i++){
//                //如果最后一个坐标的y轴比height高，直接退出
//                if((y+size)>height){
//                    break;
//                }
//                if (null != degree) {
//                    //设置水印旋转
//                    g.rotate(Math.toRadians(degree),(double) bi.getWidth() / 2, (double) bi.getHeight() / 2);
//                }
//                g.setFont(font);
//                //水印位置
//                g.drawString(word, x, y);
//                y+=(2*size);
//            }
            g.setFont(font);
            //水印位置
            g.drawString(word, x, y);
            g.dispose();
            //输出图片
            File sf = new File(output, imageName + "." + imageType);
            ImageIO.write(bi, imageType, sf); // 保存图片
            if (sf.exists() && sf.isFile()) {
                FileInputStream fis = new FileInputStream(sf);
                fileSize = fis.getChannel().size();
                System.out.println(fileSize);
            }
            result = "图片完成添加Word水印";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) {
        markImageByMoreText("", "", "", "", null, "", 0);
    }


}

